package com.example.fund.fundtrade;

import android.app.DialogFragment;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.fund.BaseActivity;
import com.example.fund.R;
import com.example.fund.TextWatcherAdapter;
import com.example.fund.util.DatabaseHelper;
import com.example.fund.util.FundTradeUtil;
import com.example.fund.util.FundUtil;
import com.example.fund.util.StringUtil;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

public class FundBatchTradeDialog extends DialogFragment {

    private SQLiteDatabase db;
    private LinearLayout root;
    private BaseActivity parentActivity;
    private int bg1 = Color.rgb(5, 167, 247);
    private int bg2 = Color.rgb(233,244,251);
    //自定义弹出选择框
    private PopupWindow popupWindow;
    private ListView popupList;
    //当前点击的TextView
    private TextView tv;
    //账户
    private EditText txtAccount;
    //基金公司
    private TextView txtCompany;
    private String[] companyList;
    //基金1
    private TextView txtFund1;
    private TextView txtFund1Number;
    private List<String> fundList;
    //基金2
    private TextView txtFund2;
    private TextView txtFund2Number;
    //交易日期
    private TextView txtTradeDate;
    private List<String> tradeDateList;
    private List<String> tempTradeDateList;
    private TextView txtTradeYear;
    private List<String> tradeYearList;
    //成交金额
    private TextView txtTradeAmount;
    //交易费率%
    private TextView txtFluctuateRate;
    //确定
    private TextView btnConfirm;

    public FundBatchTradeDialog() {
        super();
    }

    public void setParentActivity(BaseActivity parentActivity)
    {
        this.parentActivity = parentActivity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = inflater.inflate(R.layout.fundbatchtrade_dialog, null);
        this.setCancelable(false);// 设置点击屏幕Dialog不消失
        DatabaseHelper helper = new DatabaseHelper(getActivity());
        db = helper.getWritableDatabase();
        init(view);
        initListener();
        return view;
    }

    public void  init(View view)
    {
        root = (LinearLayout)view.findViewById(R.id.root);
        root.setBackgroundColor(bg2);
        //初始化自定义下拉框
        View contentView = LayoutInflater.from(view.getContext()).inflate(R.layout.popupwindow, null);
        contentView.setBackgroundColor(bg2);
        popupWindow = new PopupWindow(root, 400, 900);
        popupWindow.setContentView(contentView);
        popupList = (ListView) contentView.findViewById(R.id.popupList);
        popupList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0));
        //获取界面的控件
        txtAccount = (EditText)view.findViewById(R.id.txtAccount);
        txtCompany = (TextView)view.findViewById(R.id.txtCompany);
        txtFund1 = (TextView)view.findViewById(R.id.txtFund1);
        txtFund1Number = (TextView)view.findViewById(R.id.txtFund1Number);
        txtFund2 = (TextView)view.findViewById(R.id.txtFund2);
        txtFund2Number = (TextView)view.findViewById(R.id.txtFund2Number);
        txtTradeDate = (TextView)view.findViewById(R.id.txtTradeDate);
        txtTradeYear = (TextView)view.findViewById(R.id.txtTradeYear);
        txtTradeAmount = (TextView)view.findViewById(R.id.txtTradeAmount);
        txtFluctuateRate = (TextView)view.findViewById(R.id.txtFluctuateRate);
        btnConfirm = (TextView)view.findViewById(R.id.btnConfirm);

        companyList = FundUtil.companyNames;
        fundList = FundUtil.getAllFundName("");
        tradeDateList = FundUtil.getSHIndexDateList();
        tempTradeDateList = new LinkedList<String>();
        tradeYearList = new LinkedList<String>();
        Calendar c = Calendar.getInstance();
        for (int i=0;i<20;i++)
        {
            int year = c.get(Calendar.YEAR);
            tradeYearList.add(year+"");
            c.add(Calendar.YEAR,-1);
        }
    }

    /**
     * 注册事件
     */
    public void initListener()
    {
        //基金公司
        txtCompany.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View arg0)
            {
                initPopWindow((TextView) arg0,companyList);
            }
        });
        //基金1
        txtFund1.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View arg0)
            {
                String company = txtCompany.getText().toString();
                if (!StringUtil.isNullOrEmpty(company) && !"基金".equals(company))
                {
                    fundList = FundUtil.getAllFundName(company);
                }else {
                    fundList = FundUtil.getAllFundName("");
                }

                initPopWindow((TextView) arg0,fundList.toArray());
            }
        });
        //选择基金1后事件
        txtFund1.addTextChangedListener(new TextWatcherAdapter()
        {
            @Override
            public void afterTextChanged(Editable arg0) {
                String fundNumber = FundUtil.getFundNumber(txtFund1.getText().toString());
                txtFund1Number.setText(fundNumber);
                super.afterTextChanged(arg0);
            }
        });
        //基金2
        txtFund2.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View arg0)
            {
                String company = txtCompany.getText().toString();
                if (!StringUtil.isNullOrEmpty(company) && !"基金".equals(company))
                {
                    fundList = FundUtil.getAllFundName(company);
                }else {
                    fundList = FundUtil.getAllFundName("");
                }

                initPopWindow((TextView) arg0,fundList.toArray());
            }
        });
        //选择基金2后事件
        txtFund2.addTextChangedListener(new TextWatcherAdapter()
        {
            @Override
            public void afterTextChanged(Editable arg0) {
                String fundNumber = FundUtil.getFundNumber(txtFund2.getText().toString());
                txtFund2Number.setText(fundNumber);
                super.afterTextChanged(arg0);
            }
        });

        //交易起始日期
        txtTradeDate.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View arg0)
            {
                String year = txtTradeYear.getText().toString();
                tempTradeDateList.clear();
                for(int i=0,s=tradeDateList.size();i<s;i++)
                {
                    String deteStr = tradeDateList.get(i);
                    if (deteStr.startsWith(year))
                    {
                        tempTradeDateList.add(deteStr);
                    }
                }
                initPopWindow((TextView) arg0,tempTradeDateList.toArray());
            }
        });
        txtTradeYear.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View arg0)
            {
                initPopWindow((TextView) arg0,tradeYearList.toArray());
            }
        });
        //下拉框选中事件
        popupList.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
            {
                tv.setText(((TextView)arg1).getText());
                popupWindow.dismiss();
            }
        });

        // 按返回时关闭窗口
        getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    FundBatchTradeDialog.this.dismiss();
                    return true;
                }
                return false;
            }
        });
        //点击确定保存数据
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnConfirm_onClick(v);
            }
        });
    }

    /**
     * 点击确定保存数据
     * @param v
     */
    private void btnConfirm_onClick(View v)
    {
        String account = txtAccount.getText().toString();
        String fund1Number = txtFund1Number.getText().toString();
        String fund2Number = txtFund2Number.getText().toString();
        String amount = txtTradeAmount.getText().toString();
        String tradeDate = txtTradeDate.getText().toString();
        String fluctuateRate = txtFluctuateRate.getText().toString();

        if (StringUtil.isNullOrEmpty(account))
        {
            Toast.makeText(this.getActivity(), "请输入账户", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtil.isNullOrEmpty(fund1Number))
        {
            Toast.makeText(this.getActivity(), "请选择基金1", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtil.isNullOrEmpty(fund2Number))
        {
            Toast.makeText(this.getActivity(), "请选择基金2", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtil.isNullOrEmpty(tradeDate))
        {
            Toast.makeText(this.getActivity(), "请选择交易起始日期", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtil.isNullOrEmpty(amount) || Double.valueOf(amount)<=0)
        {
            Toast.makeText(this.getActivity(), "请输入起始金额", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtil.isNullOrEmpty(fluctuateRate) || Double.valueOf(fluctuateRate)<=0)
        {
            Toast.makeText(this.getActivity(), "请输入波动幅度", Toast.LENGTH_SHORT).show();
            return;
        }

        FundTradeUtil.addBatchTrade(account,fund1Number,fund2Number,Double.valueOf(amount),tradeDate,Double.valueOf(fluctuateRate));

        Toast.makeText(this.getActivity(), "保存成功", Toast.LENGTH_SHORT).show();
        this.dismiss();
    }

    /**
     * 初始化弹出下拉框，
     * 适用范围：时间区间、涨幅、跌幅
     * @param view
     * @param objects
     */
    @SuppressWarnings("unchecked")
    private void initPopWindow(final TextView view,final Object[] objects){
        ArrayAdapter adapter = new ArrayAdapter(view.getContext(), android.R.layout.simple_list_item_1, objects)
        {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                TextView mTextView = new TextView(view.getContext());
                mTextView.setText(objects[position].toString());
                mTextView.setTextSize(15);
                mTextView.setTextColor(bg1);
                mTextView.setPadding(30, 10, 0, 10);
                return mTextView;
            }
        };
        popupList.setAdapter(adapter);
        String text = view.getText().toString();
        for(int i=0;i<objects.length;i++)
        {
            if(text.equals(objects[i]))
            {
                popupList.setSelection(i);
                break;
            }
        }
        popupWindow.showAsDropDown(view);
        tv = view;
    }
}
